<template>
  <div class="app-container">
    <!-- 顶部控制栏 -->
    <MonitorHeader
      :connection-status="connectionStatus"
      :connection-status-text="connectionStatusText"
      :auto-refresh="autoRefresh"
      :last-update-time="lastUpdateTime"
      @toggle-auto-refresh="toggleAutoRefresh"
      @export-data="handleExport"
      @open-settings="showSettings = true"
    />

    <!-- 筛选条件 -->
    <MonitorFilter
      :device-list="deviceList"
      :query-params="queryParams"
      :date-range="dateRange"
      :time-filter="timeFilter"
      @query="handleQuery"
      @reset="resetQuery"
      @time-filter-change="setTimeFilter"
    />

    <!-- 实时数据概览 -->
    <RealTimeMetrics
      :real-time-metrics="realTimeMetrics"
      :device-status-stats="deviceStatusStats"
      :last-update-time="lastUpdateTime"
    />

    <!-- 图表分析区域 -->
    <MonitorCharts
      ref="monitorCharts"
      :chart-time-range="chartTimeRange"
      :selected-metrics="selectedMetrics"
      :chart-loading="chartLoading"
      :query-params="queryParams"
      :device-list="deviceList"
      @metrics-change="updateMainChart"
    />

    <!-- 历史数据表格 -->
    <DataTable
      :data-list="dataList"
      :total="total"
      :loading="loading"
      :selected-rows="selectedRows"
      :table-height="tableHeight"
      :table-size="tableSize"
      :query-params="queryParams"
      @refresh="handleRefresh"
      @export-table="handleExportTable"
      @table-action="handleTableAction"
      @selection-change="handleSelectionChange"
      @sort-change="handleSortChange"
      @pagination="getList"
      @view-details="viewDetails"
      @view-trend="viewTrend"
    />

    <!-- 设置对话框 -->
    <SettingsDialog
      :visible.sync="showSettings"
      :settings="settings"
      @close="showSettings = false"
      @save="saveSettings"
    />
  </div>
</template>

<script>
// API 导入
import {
  listEnergyData,
  getLatestData,
  getAllLatestCollectionData,
  getCollectionHistory,
  getCollectionStatistics,
  getChartTrendData,
  getChartDistributionData,
  getChartEfficiencyData,
  getChartLoadData
} from "@/api/energy/monitor";
import { listDevice, getAllDevicesLatestData, getDeviceStatusStatistics } from "@/api/energy/device";
import {
  getRealtimeMonitorData
} from "@/api/energy/statistics";

// 组件导入
import MonitorHeader from './components/MonitorHeader.vue';
import MonitorFilter from './components/MonitorFilter.vue';
import RealTimeMetrics from './components/RealTimeMetrics.vue';
import MonitorCharts from './components/MonitorCharts.vue';
import DataTable from './components/DataTable.vue';
import SettingsDialog from './components/SettingsDialog.vue';

// 工具方法导入
import {
  calculateAverageData,
  updateRealTimeMetrics,
  getChartParams,
  validateSettings,
  getEnergyTypeName,
  formatValue
} from './utils/monitor-utils';
import { parseTime } from '@/utils/ruoyi';

export default {
  name: "Monitor",
  components: {
    MonitorHeader,
    MonitorFilter,
    RealTimeMetrics,
    MonitorCharts,
    DataTable,
    SettingsDialog
  },
  data() {
    return {
      // 基础状态
      loading: true,
      chartLoading: false,
      showSettings: false,

      // 连接状态
      connectionStatus: 'online',
      connectionStatusText: '连接正常',

      // 自动刷新
      autoRefresh: true,
      refreshTimer: null,
      lastUpdateTime: '',

      // 时间筛选
      timeFilter: 'realtime',
      chartTimeRange: '1h',

      // 数据
      total: 0,
      dataList: [],
      deviceList: [],
      selectedRows: [],

      // 实时指标数据
      realTimeMetrics: [
        {
          label: "实时功率",
          value: "0.00",
          unit: "kW",
          icon: "el-icon-lightning",
          color: "#409EFF",
          trend: 0,
          range: "0-100kW",
          status: "normal"
        },
        {
          label: "电压",
          value: "0.00",
          unit: "V",
          icon: "el-icon-cpu",
          color: "#67C23A",
          trend: 0,
          range: "200-240V",
          status: "normal"
        },
        {
          label: "电流",
          value: "0.00",
          unit: "A",
          icon: "el-icon-connection",
          color: "#E6A23C",
          trend: 0,
          range: "0-500A",
          status: "normal"
        },
        {
          label: "温度",
          value: "0.00",
          unit: "℃",
          icon: "el-icon-thermometer",
          color: "#F56C6C",
          trend: 0,
          range: "0-80℃",
          status: "normal"
        }
      ],

      // 设备状态统计
      deviceStatusStats: [
        { label: "在线设备", count: 0, icon: "el-icon-success", color: "#67C23A" },
        { label: "离线设备", count: 0, icon: "el-icon-error", color: "#F56C6C" },
        { label: "告警设备", count: 0, icon: "el-icon-warning", color: "#E6A23C" },
        { label: "故障设备", count: 0, icon: "el-icon-close", color: "#909399" }
      ],

      // 图表选择
      selectedMetrics: ['power', 'voltage', 'current'],

      // 日期范围
      dateRange: [],

      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 20,
        deviceId: null,
        energyType: null,
        orderByColumn: 'ts',
        isAsc: 'desc'
      },

      // 表格设置
      tableHeight: 400,
      tableSize: 'medium',

      // 设置
      settings: {
        refreshInterval: 5000,
        dataRetentionDays: 30,
        enableAlerts: true,
        enableQualityCheck: true,
        enableAutoExport: false,
        exportFormat: 'xlsx'
      }
    };
  },
  created() {
    this.initData();
  },
  mounted() {
    this.updateLastUpdateTime();
    this.startAutoRefresh();
  },
  beforeDestroy() {
    this.stopAutoRefresh();
  },
  methods: {
    // ==================== 初始化方法 ====================
    async initData() {
      try {
        await Promise.all([
          this.getDeviceList(),
          this.getList(),
          this.loadRealTimeData(),
          this.loadDeviceStatusStats()
        ]);

        // 等待DOM更新后再加载图表数据
        this.$nextTick(() => {
          this.loadChartData();
        });
      } catch (error) {
        console.error('初始化数据失败:', error);
        this.$modal.msgError('数据加载失败，请刷新页面重试');
      }
    },

    async getDeviceList() {
      try {
        const response = await listDevice();
        this.deviceList = response.rows || [];
      } catch (error) {
        console.error('获取设备列表失败:', error);
      }
    },

    async getList() {
      this.loading = true;
      try {
        const params = { ...this.queryParams };
        this.addDateRange(params, this.dateRange);

        const response = await listEnergyData(params);
        this.dataList = response.rows || [];
        this.total = response.total || 0;
      } catch (error) {
        console.error('获取数据列表失败:', error);
        this.$modal.msgError('获取数据失败');
      } finally {
        this.loading = false;
      }
    },

    async loadDeviceStatusStats() {
      try {
        const response = await getDeviceStatusStatistics();
        if (response.data) {
          this.deviceStatusStats[0].count = response.data.online || 0;
          this.deviceStatusStats[1].count = response.data.offline || 0;
          this.deviceStatusStats[2].count = response.data.alarm || 0;
          this.deviceStatusStats[3].count = response.data.fault || 0;
        }
      } catch (error) {
        console.error('获取设备状态统计失败:', error);
        // 如果新接口失败，尝试从实时数据中计算状态统计
        await this.calculateStatusFromRealtime();
      }
    },

    async calculateStatusFromRealtime() {
      try {
        const response = await getRealtimeMonitorData();
        if (response.data && response.data.length > 0) {
          let online = 0, offline = 0, alarm = 0, fault = 0;

          response.data.forEach(item => {
            if (item.data && item.data.status) {
              const status = item.data.status.toString();
              switch (status) {
                case '0':
                case 'ONLINE':
                  online++;
                  break;
                case '1':
                case 'ALARM':
                  alarm++;
                  break;
                case '2':
                case 'FAULT':
                  fault++;
                  break;
                case '3':
                case 'OFFLINE':
                  offline++;
                  break;
                default:
                  offline++;
                  break;
              }
            } else {
              offline++;
            }
          });

          this.deviceStatusStats[0].count = online;
          this.deviceStatusStats[1].count = offline;
          this.deviceStatusStats[2].count = alarm;
          this.deviceStatusStats[3].count = fault;
        }
      } catch (error) {
        console.error('从实时数据计算状态统计失败:', error);
      }
    },

    // ==================== 实时数据方法 ====================
    async loadRealTimeData() {
      try {
        let data = null;

        if (this.queryParams.deviceId) {
          // 获取特定设备数据
          const selectedDevice = this.deviceList.find(d => d.deviceId === this.queryParams.deviceId);
          if (selectedDevice && selectedDevice.deviceCode) {
            const response = await getAllDevicesLatestData();
            if (response.data && response.data.length > 0) {
              data = response.data.find(d => d.deviceCode === selectedDevice.deviceCode);
            }
          }
        } else {
          // 获取所有设备的汇总数据
          const response = await getRealtimeMonitorData();
          if (response.data && response.data.length > 0) {
            data = calculateAverageData(response.data);
          }
        }

        if (data) {
          this.realTimeMetrics = updateRealTimeMetrics(this.realTimeMetrics, data);
          this.updateConnectionStatus('online');
        } else {
          this.updateConnectionStatus('warning');
        }

        this.updateLastUpdateTime();
        await this.loadChartData();

      } catch (error) {
        console.error('加载实时数据失败:', error);
        this.updateConnectionStatus('offline');
        // 尝试回退方案
        await this.loadRealTimeDataFallback();
      }
    },

    async loadRealTimeDataFallback() {
      try {
        const response = await getLatestData();
        if (response.data && response.data.length > 0) {
          const latest = response.data[0];
          this.realTimeMetrics = updateRealTimeMetrics(this.realTimeMetrics, latest);
        }
      } catch (error) {
        console.error('回退数据加载也失败:', error);
      }
    },

    updateConnectionStatus(status) {
      this.connectionStatus = status;
      const statusMap = {
        online: '连接正常',
        warning: '连接异常',
        offline: '连接断开'
      };
      this.connectionStatusText = statusMap[status] || '未知状态';
    },

    updateLastUpdateTime() {
      this.lastUpdateTime = this.parseTime(new Date(), '{y}-{m}-{d} {h}:{i}:{s}');
    },

    // ==================== 自动刷新方法 ====================
    startAutoRefresh() {
      if (this.autoRefresh && !this.refreshTimer) {
        this.refreshTimer = setInterval(() => {
          this.loadRealTimeData();
        }, this.settings.refreshInterval);
      }
    },

    stopAutoRefresh() {
      if (this.refreshTimer) {
        clearInterval(this.refreshTimer);
        this.refreshTimer = null;
      }
    },

    toggleAutoRefresh() {
      this.autoRefresh = !this.autoRefresh;
      if (this.autoRefresh) {
        this.startAutoRefresh();
      } else {
        this.stopAutoRefresh();
      }
    },

    // ==================== 图表方法 ====================
    async loadChartData() {
      this.chartLoading = true;
      try {
        await Promise.all([
          this.loadMainTrendChart(),
          this.loadEnergyDistributionChart(),
          this.loadEfficiencyChart(),
          this.loadLoadAnalysisChart()
        ]);
      } finally {
        this.chartLoading = false;
      }
    },

    async loadMainTrendChart() {
      try {
        const params = getChartParams(this.chartTimeRange, this.queryParams, this.dateRange);
        const response = await getChartTrendData(params);
        this.$refs.monitorCharts?.updateMainTrendChart(response.data || []);
      } catch (error) {
        console.error('加载主趋势图失败:', error);
      }
    },

    async loadEnergyDistributionChart() {
      try {
        const params = getChartParams(this.chartTimeRange, this.queryParams, this.dateRange);
        console.log('能耗分布图请求参数:', params);

        const response = await getChartDistributionData(params);
        console.log('能耗分布图API响应:', {
          status: response.code,
          message: response.msg,
          data: response.data,
          dataLength: response.data ? response.data.length : 0
        });

        // 详细打印数据内容
        if (response.data && response.data.length > 0) {
          console.log('能耗分布图数据详情:', response.data);
          response.data.forEach((item, index) => {
            console.log(`数据项${index}:`, item);
          });
        } else {
          console.warn('能耗分布图API返回空数据');
        }

        this.$refs.monitorCharts?.updateEnergyDistributionChart(response.data || []);
      } catch (error) {
        console.error('加载能耗分布图失败:', error);
      }
    },

    async loadEfficiencyChart() {
      try {
        let data = [];
        if (this.queryParams.deviceId) {
          const selectedDevice = this.deviceList.find(d => d.deviceId === this.queryParams.deviceId);
          if (selectedDevice && selectedDevice.deviceCode) {
            const params = getChartParams(this.chartTimeRange, this.queryParams, this.dateRange);
            const response = await getChartEfficiencyData(selectedDevice.deviceCode, params);
            data = response.data || [];
          }
        }
        // 无论是否有设备选择，都更新图表（组件内部会处理空数据情况）
        this.$refs.monitorCharts?.updateEfficiencyChart(data);
      } catch (error) {
        console.error('加载效率分析图失败:', error);
        // 即使出错也要更新图表，显示空数据状态
        this.$refs.monitorCharts?.updateEfficiencyChart([]);
      }
    },

    async loadLoadAnalysisChart() {
      try {
        let data = [];
        if (this.queryParams.deviceId) {
          const selectedDevice = this.deviceList.find(d => d.deviceId === this.queryParams.deviceId);
          if (selectedDevice && selectedDevice.deviceCode) {
            const params = getChartParams(this.chartTimeRange, this.queryParams, this.dateRange);
            const response = await getChartLoadData(selectedDevice.deviceCode, params);
            data = response.data || [];
          }
        }
        // 无论是否有设备选择，都更新图表（组件内部会处理空数据情况）
        this.$refs.monitorCharts?.updateLoadAnalysisChart(data);
      } catch (error) {
        console.error('加载负载分析图失败:', error);
        // 即使出错也要更新图表，显示空数据状态
        this.$refs.monitorCharts?.updateLoadAnalysisChart([]);
      }
    },

    // ==================== 事件处理方法 ====================
    handleQuery(data) {
      this.queryParams = { ...this.queryParams, ...data.queryParams };
      this.dateRange = [...data.dateRange];
      this.queryParams.pageNum = 1;
      this.getList();
      this.loadChartData();
    },

    resetQuery() {
      this.dateRange = [];
      this.queryParams.deviceId = null;
      this.queryParams.energyType = null;
      this.handleQuery({ queryParams: this.queryParams, dateRange: this.dateRange });
    },

    handleRefresh() {
      this.getList();
      this.loadRealTimeData();
      this.loadChartData();
    },

    setTimeFilter(filter) {
      this.timeFilter = filter;
      this.chartTimeRange = filter === 'realtime' ? '1h' : filter;
      this.loadChartData();
    },



    updateMainChart() {
      this.loadMainTrendChart();
    },

    // ==================== 表格相关方法 ====================
    handleSelectionChange(selection) {
      this.selectedRows = selection;
    },

    handleSortChange({ column, prop, order }) {
      this.queryParams.orderByColumn = prop;
      this.queryParams.isAsc = order === 'ascending' ? 'asc' : 'desc';
      this.getList();
    },

    handleTableAction(command) {
      switch (command) {
        case 'columns':
          this.$message.info('自定义列功能开发中...');
          break;
        case 'density':
          this.tableSize = this.tableSize === 'medium' ? 'small' : 'medium';
          break;
        case 'fullscreen':
          this.tableHeight = this.tableHeight === 400 ? window.innerHeight - 300 : 400;
          break;
      }
    },

    viewDetails(row) {
      this.$alert(`
        <div style="text-align: left;">
          <p><strong>设备编码：</strong>${row.deviceCode}</p>
          <p><strong>能耗类型：</strong>${this.getEnergyTypeName(row.energyType)}</p>
          <p><strong>电压：</strong>${this.formatValue(row.voltage, 2)} V</p>
          <p><strong>电流：</strong>${this.formatValue(row.current, 2)} A</p>
          <p><strong>功率：</strong>${this.formatValue(row.power, 2)} kW</p>
          <p><strong>累计能耗：</strong>${this.formatValue(row.totalEnergy, 2)} kWh</p>
          <p><strong>温度：</strong>${this.formatValue(row.temperature, 1)} ℃</p>
          <p><strong>采集时间：</strong>${this.parseTime(row.ts, '{y}-{m}-{d} {h}:{i}:{s}')}</p>
        </div>
      `, '数据详情', {
        dangerouslyUseHTMLString: true,
        customClass: 'detail-dialog'
      });
    },

    viewTrend(row) {
      this.queryParams.deviceId = row.deviceId;
      this.loadChartData();
      this.$message.success('已切换到该设备的趋势图');
    },

    handleExport() {
      this.$modal.confirm('是否确认导出所有监控数据项?').then(() => {
        this.download('energy/monitor/export', {
          ...this.queryParams
        }, `monitor_data_${new Date().getTime()}.xlsx`);
      });
    },

    handleExportTable() {
      if (this.selectedRows.length === 0) {
        this.$modal.msgWarning('请选择要导出的数据');
        return;
      }

      this.$modal.confirm(`是否确认导出选中的${this.selectedRows.length}条数据?`).then(() => {
        const ids = this.selectedRows.map(row => row.id);
        this.download('energy/monitor/export', { ids: ids.join(',') }, `selected_data_${new Date().getTime()}.xlsx`);
      });
    },

    saveSettings(newSettings) {
      const validation = validateSettings(newSettings);
      if (!validation.isValid) {
        this.$message.warning(validation.errors[0]);
        return;
      }

      this.settings = { ...newSettings };

      // 重新设置刷新间隔
      this.stopAutoRefresh();
      if (this.autoRefresh) {
        this.startAutoRefresh();
      }

      this.showSettings = false;
      this.$modal.msgSuccess('设置保存成功');
    },

    // ==================== 工具方法 ====================
    parseTime,
    getEnergyTypeName,
    formatValue
  }
};
</script>

<style lang="scss" scoped>
@import './styles/monitor.scss';
</style>
